package com.happle.gcmclient;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.happle.gcmclient.adapter.MessageAdapter;
import com.happle.gcmclient.backendmanager.BackendManager;
import com.happle.gcmclient.backendmanager.task.DeleteConversationTask;
import com.happle.gcmclient.backendmanager.task.UpdateConversationTask;
import com.happle.gcmclient.config.CommonUtilities;
import com.happle.gcmclient.config.Constants;
import com.happle.gcmclient.config.GlobalValue;
import com.happle.gcmclient.dialog.AddLanguageDialog;
import com.happle.gcmclient.dialog.AddLanguageDialog.SelectLanguageListener;
import com.happle.gcmclient.managers.LngManager;
import com.happle.gcmclient.managers.MessagesManager;
import com.happle.gcmclient.obj.ConversationObj;
import com.happle.gcmclient.obj.LngObj;
import com.happle.gcmclient.obj.MessageObj;

public class MessageListActivity extends BaseActivity {

	// params
	public static final String TAG = "MessageListActivity";
	public static boolean MAIsRunning = false;
	public static boolean HasANewMSG = false;
	public static MessageObj SentMessage;
	private ListView lsvMessage;
	private List<MessageObj> listMessage;
	private MessageAdapter messageAdapter;
	private MessagesManager msgManager;
	private List<LngObj> listLanguages;
	private LngManager lngManager;
	public String[] items;
	// CONTROL vars
	private SendMessageTask smTask;
	protected UpdateConversationTask updTask;
	protected DeleteConversationTask delTask;
	private IntentFilter messageFilter;
	private GCMReceiver gcmMessageReceier;
	private String broadcastMessage;
	private boolean swapScreen = false;
	private String current_wave_id = null;
	private String current_lng_id = null;
	private View footerView;
	private Bundle extras;
	private EditText txtMessage;
	private Button btnSend;
	private Spinner spinnerLng;
    private RelativeLayout spinnerLngLayout;
	public MessageObj NewMessage;
	private ConversationObj convObj;
	private List<LngObj> listAllLanguages;
	private ArrayAdapter<String> lngAdapter;
	private int prevSpinnerPosition;
	private boolean isOtherLngPressed = false;

	private boolean isNeedUpdateListConversation = false;
	private boolean isPushFromListConversation = false;
	private boolean isPushFromNotification = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setContentView(R.layout.message_listview);
		initUI(savedInstanceState);
		initReceiver();
		startSyncService();
		if (getIntent()
				.getBooleanExtra(Constants.PUSH_FROM_CONVERSATION, false)) {
			isPushFromListConversation = true;
		}
		MAIsRunning = true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
        if (current_wave_id != null){
            if (msgManager == null)
                msgManager = new MessagesManager(self);
            convObj = msgManager.getConversationObj(current_wave_id);
            if (convObj.is_conv_status()) {
                inflater.inflate(R.menu.activity_message, menu);
            } else {
                inflater.inflate(R.menu.activity_message_limited, menu);
            }
          }
//          else {
//            inflater.inflate(R.menu.activity_message, menu);
//        }
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		int taskResult = -1;
		if (current_wave_id != null) {
			if (msgManager == null)
				msgManager = new MessagesManager(self);
			convObj = msgManager.getConversationObj(current_wave_id);
			isNeedUpdateListConversation = true;
			switch (item.getItemId()) {
			case R.id.menu_close_conversation:
				taskResult = msgManager.closeConversation(current_wave_id);
				taskResult = updateConversation(convObj,
						Constants.MSG_STATUS_CLOSED, GlobalValue.registerId);
				initData(current_wave_id);
				return true;
			case R.id.menu_delete_conversation:
				taskResult = msgManager.deleteConversation(current_wave_id);
				taskResult = deleteConversation(convObj, GlobalValue.registerId);
				onBackHeaderClick();
				onBackPressed();
				return true;
			}
		} else {
			onBackHeaderClick();
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		int position = info.position;
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if (listMessage.get(position).is_msg_status()) {
			inflater.inflate(R.menu.activity_messages_list, menu);
		} else {
			inflater.inflate(R.menu.activity_messages_list_limited, menu);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int taskResult = -1;
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		if (info != null) {
			MessageObj messageToDelete = (MessageObj) listMessage
					.get(info.position);
			if (current_wave_id != null) {
				if (msgManager == null)
					msgManager = new MessagesManager(self);
				ConversationObj clicked_conversation = msgManager
						.getConversationObj(current_wave_id);
				isNeedUpdateListConversation = true;
				switch (item.getItemId()) {
				case R.id.menu_contx_delete_message:
					if (clicked_conversation.get_msgs_count() < 2) {
						deleteConversationTask(clicked_conversation);
					}
					msgManager
							.deleteMessage(messageToDelete.get_msg_id_local());
					initData(current_wave_id);
					return true;
				case R.id.menu_contx_close_conversation:
					taskResult = msgManager
							.closeConversation(clicked_conversation
									.get_wave_id());
					taskResult = updateConversation(clicked_conversation,
							Constants.MSG_STATUS_CLOSED, GlobalValue.registerId);
					initData(current_wave_id);
					return true;
				case R.id.menu_contx_delete_conversation:
					// deleteConversationTask(clicked_conversation);
					taskResult = msgManager
							.deleteConversation(clicked_conversation
									.get_wave_id());
					taskResult = deleteConversation(clicked_conversation,
							GlobalValue.registerId);
					onBackHeaderClick();
					onBackPressed();
					return true;
				default:
					return super.onContextItemSelected(item);
				}
			} else {
				onBackHeaderClick();
			}
		}
		return false;
	}

	private void deleteConversationTask(ConversationObj clicked_conversation) {
		int taskResult = -1;
		taskResult = msgManager.deleteConversation(clicked_conversation
				.get_wave_id());
		taskResult = deleteConversation(clicked_conversation,
				GlobalValue.registerId);
		onBackHeaderClick();
		onBackPressed();
	}

	private int updateConversation(ConversationObj convObj, int conv_status,
			String registration_id) {
		int taskResult = -1;
		try {
			updTask = new UpdateConversationTask(convObj, conv_status,
					registration_id, self);
			updTask.execute();
			taskResult = updTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return taskResult;
	}

	private int deleteConversation(ConversationObj convObj,
			String registration_id) {
		int taskResult = -1;
		try {
			delTask = new DeleteConversationTask(convObj, registration_id, self);
			delTask.execute();
			taskResult = delTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return taskResult;
	}

	private void initUI(Bundle savedInstanceState) {
		initHeader();
		setHeaderTitle(getString(R.string.titleMessagesListActivity), Constants.TITLE_MESSAGESLIST_IMAGE_NUM);
		lsvMessage = (ListView) findViewById(R.id.lsvMessage);
		registerForContextMenu(lsvMessage);
		swapScreen = (savedInstanceState != null && savedInstanceState
				.containsKey("swapScreen")) ? savedInstanceState
				.getBoolean("swapScreen") : swapScreen;
		txtMessage = (EditText) findViewById(R.id.txtMsg);
		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(sendListener);
		spinnerLng = (Spinner) findViewById(R.id.message_lng_spinner);
        spinnerLngLayout = (RelativeLayout) findViewById(R.id.message_spinner_layout);
		extras = getIntent().getExtras();
		NewMessage = new MessageObj();
		if (extras != null) {
			String requestCode = extras.getString(Constants.REQUEST_CODE);
			Intent i = getIntent();
			extras = getIntent().getExtras();

			switch (Integer.parseInt(requestCode)) {
			case Constants.REQUEST_CODE_UPD:
				current_wave_id = extras.getString(Constants.WAVE_ID);
				current_lng_id = extras.getString(Constants.lng_id_p);
				NewMessage.set_wave_id(current_wave_id);
				initData(current_wave_id);
                spinnerLngLayout.setVisibility(View.GONE);
				if (swapScreen) {
					txtMessage.setText(savedInstanceState
							.getString("BroadcastMessage"));
				}
				break;

			case Constants.REQUEST_CODE_ADD:
				if (!swapScreen) {
					current_wave_id = null;
					//txtMessage.requestFocus();
				} else if (swapScreen) {
					txtMessage.setText(savedInstanceState
							.getString("BroadcastMessage"));
					current_wave_id = savedInstanceState
							.getString("current_wave_id");
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(txtMessage.getWindowToken(), 0);
				}
				initLng();
				break;
			case Constants.REQUEST_CODE_NOTIF:
				if (!swapScreen) {
					NewMessage = (MessageObj) i
							.getParcelableExtra(Constants.KEY_MESSAGE_OBJECT);
					current_wave_id = NewMessage.get_wave_id();
					current_lng_id = NewMessage.get_lng_id();
					isPushFromNotification = true;
				} else if (swapScreen) {
					txtMessage.setText(savedInstanceState
							.getString("BroadcastMessage"));
					current_wave_id = savedInstanceState
							.getString("current_wave_id");
				}
				initData(current_wave_id);
                spinnerLngLayout.setVisibility(View.GONE);
				break;
			}
		} else {
			initLng();
		}
        txtMessage.requestFocus();
        //flag
//        txtMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                boolean handled = false;
//                if (actionId == EditorInfo.IME_ACTION_SEND) {
//                    sendMessageToServer();
//                    handled = true;
//                }
//                return handled;
//            }
//        });

        final View activityRootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
        final View msgLayout = (ViewGroup)findViewById(R.id.txtMsgLayout);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(r);

                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff < 100) {
                    //txtMessage.setLines(1);
                    //scrollMyListViewToBottom();
                } else {
//                    int heighListview = msgLayout.getHeight()+50;
//                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) lsvMessage.getLayoutParams();
//                    params.setMargins(0,100,0,heighListview);
//                    lsvMessage.setLayoutParams(params);
//                    //scrollMyListViewToBottom();
                      //txtMessage.setMinLines(4);
                }
            }
        });
	}

	private void initData(String wave_id) {
		listMessage = new ArrayList<MessageObj>();
		if (msgManager == null)
			msgManager = new MessagesManager(self);
		listMessage = msgManager.getConversation(wave_id);
		bindDataToList();
		if (!listMessage.get(0).is_msg_status()) {
			btnSend.setEnabled(false);
			txtMessage.setEnabled(false);
			btnSend.setText(R.string.closedConversationShort);
		}
	}

	private void initLng() {
		listLanguages = new ArrayList<LngObj>();
		if (lngManager == null) {
			lngManager = new LngManager(self);
		}
		listLanguages = lngManager.getSelectedLanguages(true);
		items = new String[listLanguages.size() + 1];
		int i = 0;
		for (LngObj item : listLanguages) {
			items[i] = item.get_lng_name();
			i++;
		}

		items[i] = Constants.ADD_LNG_BTN;
		lngAdapter = new ArrayAdapter<String>(this,
				R.layout.simple_spinner_item, items);
		lngAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
		spinnerLng.setAdapter(lngAdapter);
//        //variant 1
//        lngAdapter = new SpinnerLngAdapter(self,
//                android.R.layout.simple_spinner_dropdown_item, items);
//        lngAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinnerLng.setAdapter(lngAdapter);
		addListenerOnSpinnerItemSelection();
	}

	public void addListenerOnSpinnerItemSelection() {
		spinnerLng.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				if (pos == (items.length - 1)) {
					isOtherLngPressed = true;
					// spinnerLng.setSelection(prevSpinnerPosition);
					// Show Add new language dialog when select last item
					new AddLanguageDialog(self, new SelectLanguageListener() {

						@Override
						public void onSelect(int index, LngObj languageObject,
								List<LngObj> listLanguages) {
							new updateLanguageTask(languageObject).execute();
							initLng();
							// Set current spinner value with new selected
							// language
							int spinnerPosition = lngAdapter
									.getPosition(languageObject.get_lng_name());
							spinnerLng.setSelection(spinnerPosition);
							prevSpinnerPosition = spinnerLng
									.getSelectedItemPosition();
							isOtherLngPressed = false;
						}
					}).show();

				} else {
					prevSpinnerPosition = spinnerLng.getSelectedItemPosition();
					if (!isOtherLngPressed) {
						// Check if language changed , if yes : show toast
						// message
						String newLanguage = items[pos];
						if (TextUtils.isEmpty(CommonUtilities.getInstance(self)
								.pullPreferences(self, Constants.KEY_LANGUAGE))
								|| !CommonUtilities
										.getInstance(self)
										.pullPreferences(self,
												Constants.KEY_LANGUAGE)
										.equalsIgnoreCase(newLanguage)) {
							showToastMessage(getString(R.string.message_alert_change_message)
									+ newLanguage);
							CommonUtilities.getInstance(self).savePreverences(
									self, Constants.KEY_LANGUAGE, newLanguage);
						}
					}
				}
				if (spinnerLng.getSelectedItemPosition() == (items.length - 1)) {
					spinnerLng.setSelection(prevSpinnerPosition);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				prevSpinnerPosition = spinnerLng.getSelectedItemPosition();
			}
		});
	}

	private void updateList(MessageObj newItem) {
		if (listMessage == null)
			listMessage = new ArrayList<MessageObj>();
		listMessage.add(newItem);
		if (messageAdapter == null) {
			messageAdapter = new MessageAdapter(self, listMessage);
			lsvMessage.setAdapter(messageAdapter);
		}
		messageAdapter.notifyDataSetChanged();
		scrollMyListViewToBottom();
	}

	private void bindDataToList() {
		messageAdapter = new MessageAdapter(self, listMessage);

		lsvMessage.setAdapter(messageAdapter);
		scrollMyListViewToBottom();
	}

	private void scrollMyListViewToBottom() {
		lsvMessage.post(new Runnable() {
			@Override
			public void run() {
				lsvMessage.setSelection(messageAdapter.getCount() - 1);
			}
		});
	}

	private OnClickListener sendListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (TextUtils.isEmpty(txtMessage.getText())) {
				Toast.makeText(self, R.string.enterMessage, Toast.LENGTH_SHORT)
						.show();
				return;
			}
			sendMessageToServer();
		}
	};

	private void initReceiver() {
		gcmMessageReceier = new GCMReceiver();
		messageFilter = new IntentFilter();
		messageFilter.addAction(Constants.ACTION_ON_NEW_MESSAGE);
	}

	BroadcastReceiver gcmReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			Intent i = getIntent();
			MessageObj addMsg = (MessageObj) i
					.getParcelableExtra(MessageObj.class.getCanonicalName());
			if (addMsg != null) {
				if (current_wave_id.equals(addMsg.get_wave_id())) {
					initData(current_wave_id);
					if (msgManager == null)
						msgManager = new MessagesManager(self);
					msgManager.readNewMessages(current_wave_id);
				} else {
					GCMIntentService.generateNotification(context, addMsg);
				}
				isNeedUpdateListConversation = true;
			}
		}
	};

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		broadcastMessage = savedInstanceState.getString("BroadcastMessage");
		swapScreen = savedInstanceState.getBoolean("swapScreen");
		current_wave_id = savedInstanceState.getString("current_wave_id");
        //changeSpinnerAppearance(0);
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putString("BroadcastMessage", txtMessage.getText()
				.toString());
		savedInstanceState.putBoolean("swapScreen", true);
		savedInstanceState.putString("current_wave_id", current_wave_id);
	}

	@Override
	public void onResume() {
		super.onResume();
		reloadLanguage();
		registerReceiver(gcmMessageReceier, messageFilter);
		String msg = getIntent().getStringExtra(Constants.FIELD_MESSAGE);
		MAIsRunning = true;
		if (HasANewMSG) {
			if (SentMessage.get_wave_id().equals(current_wave_id)) {
				initData(current_wave_id);
				HasANewMSG = false;
			}
		}

		hideKeyboard();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(gcmMessageReceier);
		MAIsRunning = false;
	}

	public void sendMessageToServer() {
		txtMessage.setEnabled(false);
		smTask = new SendMessageTask(GlobalValue.registerId);
		smTask.execute();
	}

	class SendMessageTask extends AsyncTask<Void, Void, Integer> {
		Context context;
		private String regId;

		public SendMessageTask(String reg_id) {
			// TODO Auto-generated constructor stub
			this.regId = reg_id;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			int response = Constants.FAILED;
			NewMessage = new MessageObj();
			try {

				String msg_id_local = CommonUtilities.getInstance(self)
						.generateGUID(context);
				NewMessage.set_msg_id_local(msg_id_local);
				NewMessage.set_message(txtMessage.getText().toString());
				NewMessage.set_msg_order(Constants.MESSAGE_ROOT);
				NewMessage.set_msg_status(true);
				NewMessage.set_is_owner(true);
				NewMessage.set_is_sent(false);
				NewMessage.set_datetime(new Date());
				// add new message
				if (current_wave_id == null || current_wave_id.length() < 2) {
					// generate new conversation id - current_wave_id
					current_wave_id = CommonUtilities.getInstance(self)
							.generateGUID(context);
					current_lng_id = listLanguages.get(
							spinnerLng.getSelectedItemPosition()).get_lng_id();
				}
				try {
					NewMessage.set_lng_id(current_lng_id);
					NewMessage.set_wave_id(current_wave_id);
					if (msgManager == null)
						msgManager = new MessagesManager(self);
					NewMessage = msgManager.addMessage(NewMessage);
				} catch (Exception e) {

					Log.d(TAG, "Add message to db error");
					e.printStackTrace();
				}
				response = backendManager.sendMessage(NewMessage, regId);
				if (response == 1) {
					NewMessage.set_is_sent(true);
					msgManager.updateMessage(NewMessage);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return response;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			//spinnerLng.setVisibility(View.GONE);
            spinnerLngLayout.setVisibility(View.GONE);
			isNeedUpdateListConversation = true;

			txtMessage.setEnabled(true);
			txtMessage.setText("");

			closeProgressDialog();
			getIntent().removeExtra(Constants.REQUEST_CODE);
			getIntent().putExtra(Constants.FIELD_REQUEST_CODE,
					String.valueOf(Constants.REQUEST_CODE_UPD));
			getIntent().removeExtra(Constants.WAVE_ID);
			getIntent().putExtra(Constants.WAVE_ID, current_wave_id);
			getIntent().removeExtra(Constants.lng_id_p);
			getIntent().putExtra(Constants.lng_id_p, current_lng_id);
			try {
				updateList(NewMessage);
				NewMessage = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private class updateLanguageTask extends AsyncTask<Void, Void, Integer> {
		private LngObj lng;

		public updateLanguageTask(LngObj lng) {
			this.lng = lng;
		}

		@Override
		protected Integer doInBackground(Void... params) {
			BackendManager bManager = new BackendManager();
			int taskResult = -1;
			try {
				taskResult = bManager.updateLanguage(lng,
						GlobalValue.registerId);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return taskResult;
		}

		@Override
		protected void onPostExecute(Integer result) {
			closeProgressDialog();
			lng.set_is_sent((result == 1) ? true : false);
			// Update local database
			lngManager.updateLngSettings(lng);
		}

		@Override
		protected void onPreExecute() {
			showProgressDialog();
		}

	}

	private class GCMReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// Intent i = getIntent();
			MessageObj addMsg = (MessageObj) intent
					.getParcelableExtra(Constants.KEY_MESSAGE_OBJECT);
			if (addMsg != null) {
				if (current_wave_id.equals(addMsg.get_wave_id())) {
					if (addMsg.is_msg_status())
						updateList(addMsg);
					else
					{
						if (convObj == null){
                            convObj = msgManager.getConversationObj(current_wave_id);
                        }
						convObj.set_msg_status(addMsg.is_msg_status());
						msgManager.closeConversation(addMsg.get_wave_id());
                        addMsg.set_message(getResources().getString(R.string.closedConversationLong));
						initData(addMsg.get_wave_id());
					}

				} else {
					GCMIntentService.generateNotification(context, addMsg);
				}

				isNeedUpdateListConversation = true;
			}
		}
	};

	@Override
	protected void onBackHeaderClick() {
		handleBack();
	}

	@Override
	public void onBackPressed() {

		handleBack();
	}

	private void handleBack() {
		if (isNeedUpdateListConversation && isPushFromListConversation) {
			setResult(
					RESULT_OK,
					getIntent().putExtra(
							Constants.FIELD_NEED_UPADATE_LIST_CONVERSATION,
							true));
			finish();
		} else

		if (isPushFromNotification) {
			// Redirect to Home if this screen opened when click into a
			// notification
			gotoActivity(self, MainActivity.class);
			finish();

		} else
			super.onBackPressed();

	}

	private void reloadLanguage() {

		setHeaderTitle(getString(R.string.titleMessagesListActivity), Constants.TITLE_MESSAGESLIST_IMAGE_NUM);
		updateStatusTitle();
	}
}
